package com.varian.gateway.filter;

import com.varian.gateway.constant.GatewayConstant;
import com.varian.tool.Func;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author ben
 * @since 2024/7/18
 */
@Slf4j
public class GlobalRequestLogFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("request: {}", exchange.getRequest().getPath());
        ServerHttpRequest request = exchange.getRequest().mutate()
                .headers(httpHeaders -> httpHeaders.add(Func.TRACE_ID, Func.nextTraceId()))
                .build();
        return chain.filter(exchange.mutate().request(request).build());
    }

    @Override
    public int getOrder() {
        return GatewayConstant.REQUEST_LOG_FILTER_ORDER;
    }
}
